import json
from flask import Blueprint, jsonify, request, redirect
from flask_restful import Api,reqparse,Resource
from models.user.user import *
from db import db


shopping_bp = Blueprint('shopping',__name__,url_prefix='/shop')
api = Api(shopping_bp)

# 展示数据购物车
class Getshopping(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        args = req.parse_args()
        list = []
        sql = "select * from cart where cart.userid=%d"%int(args['userid'])
        res = db.find_all(sql)
        for i in res:
            sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
            res1 = db.find_all(sql1)
            for j in res1:
                list.append({
                    'id':j['id'],
                    'title':j['title'],
                    'price':j['price'],
                    'count':i['count'],
                    'url':j['url'],
                    'amount':(j['price'] * i['count'])
                })
                tmoney = j['price'] * i['count']
                cid = i['cid']
                money = j['price']
                count = i['count']
                return jsonify({'code':200,'msg':'ok','data':list,"tmoney": tmoney, "cid": cid,'money':money,'count':count})

api.add_resource(Getshopping,'/getshop')



# 购物车数量加
class Add_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()
        print(args['id'],12222222222)

        if not all({args['id'],args['userid']}):
            return jsonify({'code':400,'msg':'数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d"%(int(args['userid']),int(args['id']))
        res = db.find_all(sql)
        print(res,8888888)
        for i in res:
            sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d"%(int(i['userid']),int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'加成功'})
api.add_resource(Add_count,'/addcount')


# 购物车数量减
class Min_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()
        print(args['id'], 12222222222)

        if not all({args['id'], args['userid']}):
            return jsonify({'code': 400, 'msg': '数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
        res = db.find_all(sql)
        print(res, 8888888)
        for i in res:
            sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'减成功'})
api.add_resource(Min_count,'/mincount')

# 删除购物车数据
class Del_count(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('id')
        args = req.parse_args()

        if not all({args['id'], args['userid']}):
            return jsonify({'code': 400, 'msg': '数据不存在'})

        sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
        res = db.find_all(sql)
        for i in res:
            sql1 = "delete from Cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
            db.add(sql1)
            db.commit()
        return jsonify({'code':200,'msg':'ok'})
api.add_resource(Del_count,'/delcount')



import random
import datetime
from utils.comm import get_ali_object
# 调用支付宝  进行购买
class Zf_shop(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('userid')
        req.add_argument('cid')
        req.add_argument('tmoney')
        req.add_argument('money')
        req.add_argument('count')
        args = req.parse_args()
        create_time = datetime.date.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
        update_time = datetime.date.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')
        order_no =str(random.randint(1000,9999))
        sql = "insert into orders(create_time,update_time,order_no,userid,price,courseid,tmoney,number,status) values " \
              "('%s','%s','%d','%d','%d','%d','%d','%d','%d')"\
              %(str(create_time),str(update_time),int(order_no),int(args['userid']),int(args['money']),int(args['cid']),int(args['tmoney']),int(args['count']),int(2))
        db.add(sql)
        db.commit()
        # 支付页面 支付
        pay = get_ali_object()
        query_params = pay.direct_pay(
           subject='购物车订单',  # 商品简单描述
            out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
            total_amount=args['tmoney'],  # 交易金额(单位: 元 保留俩位小数)
        )
        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
        return jsonify({
            'code': 200,
            'url': pay_url
        })

api.add_resource(Zf_shop,'/zfshop')


#评论
from models.user.user import db
@shopping_bp.route("/crecom",methods=['POST'])
def createes():
    data = json.loads(request.data)
    title = data['title']
    userid = data['userid']
    pid = data['pid']
    print(userid,pid,title)
    if not pid:
        #首个评论
        comm = Comment(title=title,userid=userid,typepid=1,pid=0)
        db.session.add(comm)
        print(">>>>....")
        db.session.commit()
    else:
        com = Comment.query.filter(Comment.id==pid).first()
        print("com",com.id)
        if com:
            coms = Comment(title=title,userid=userid,typepid=2,pid=com.id)
            db.session.add(coms)
            print(coms,">?")
            coms_info = Comment.query.filter(Comment.pid==pid).first()
            print(coms_info,"///")
            if not coms_info:
                coms.is_last = 1
                print("11")
            else:
                coms.is_last = 0
                print("00")
            db.session.commit()
        else:
            return jsonify({"code":404,"msg":"评论已删除"})
    return jsonify({"code":200,"msg":"ok"})


#获取评论
def showuser(data):   #封装方法 也可以写进类视图中
    list2=[]
    dict2={}
    for i in data:
        k = i['id']
        dict2[k]=i

    for j in data:
        pid=j['pid']
        if pid == 0:   #如果为空说明是第一级
            list2.append(j)
        else:
            if 'son' not in dict2[pid]:   #判断是否有下级分类
                dict2[pid]['son'] = []
            dict2[pid]['son'].append(j)   #添加进去
    return list2

class Comments(Resource):
    def get(self):
        user_info = Comment.query.all()
        user_data = []
        for i in user_info:
            a = {
                'id':i.id,
                'title': i.title,
                'tcount': i.tcount,
                'tviews': i.tviews,
                'is_last': i.is_last,
                'is_top': i.is_top,
                'userid': i.userid,
                'typepid': i.typepid,
                'pid': i.pid,
            }
            user_data.append(a)
        ss=showuser(user_data)    #调用方法 并传参
        return jsonify({'code':200,'data':ss})
api.add_resource(Comments,"/comment")



